package rs.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import rs.util.CanonicalString;

/* Classe responsabile del parsing di un JSON relativo agli utenti simili ad un utente */
public class NeighboursParser {

	public List<String> parse(String response) {
		List<String> user_list = new ArrayList<String>();
		if (!response.substring(2,7).equals("error")) {
			try {					
				JSONObject json = (JSONObject) new JSONParser().parse(response);
				JSONObject neighbours = (JSONObject) json.get("neighbours");

				Object users_array = neighbours.get("user");
				if (users_array == null) {
					return user_list;
				}
				else if (users_array instanceof JSONObject) {
					addToList(user_list, users_array);
				}
				else {
					for (Object obj : (JSONArray)users_array) {
						addToList(user_list, obj);
					}
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return user_list;
	}

	private void addToList(List<String> users, Object obj) {
		JSONObject json_obj = (JSONObject) obj;
		String user_name = (String) json_obj.get("name");
		users.add(new CanonicalString(user_name).toString());
	}

}
